<template>
  <div class="user-list-container">
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <el-button type="primary" @click="$router.push('/user/add')">新增用户</el-button>
    </div>

    <div class="content-container">
      <!-- 搜索区域 -->
      <div class="section-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item>
            <el-input v-model="searchForm.username" placeholder="用户名" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="searchForm.phone" placeholder="手机号" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="searchForm.status" placeholder="用户状态" clearable>
              <el-option label="正常" value="正常"></el-option>
              <el-option label="禁用" value="禁用"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="section-card">
        <el-table :data="tableData" border style="width: 100%" v-loading="loading">
          <el-table-column type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="username" label="用户名" min-width="120"></el-table-column>
          <el-table-column prop="nickname" label="昵称" min-width="120"></el-table-column>
          <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
          <el-table-column prop="points" label="积分" width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.points }} 分</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '正常' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" label="注册时间" width="160"></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="handlePoints(scope.row)">积分明细</el-button>
              <el-button type="text" size="small" @click="handleResetPassword(scope.row)">重置密码</el-button>
              <el-button
                type="text"
                size="small"
                :class="{'delete-btn': true}"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
    </div>

    <!-- 积分明细弹窗 -->
    <el-dialog title="积分明细" :visible.sync="pointsDialogVisible" width="800px">
      <div class="user-info">
        <span class="user-label">用户名：</span>
        <span class="user-value">{{ currentUser.username }}</span>
        <span class="user-label">当前积分：</span>
        <span class="user-value highlight">{{ currentUser.points }} 分</span>
      </div>

      <el-table :data="pointsRecords" border style="width: 100%" v-loading="pointsLoading">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.type === '收入' ? 'success' : 'danger'">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="积分" width="100">
          <template slot-scope="scope">
            <span
              :class="{'income': scope.row.type === '收入', 'expense': scope.row.type === '支出'}"
            >{{ scope.row.type === '收入' ? '+' : '-' }}{{ scope.row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200"></el-table-column>
        <el-table-column prop="createdAt" label="时间" width="160"></el-table-column>
        <el-table-column prop="balance" label="账户余额" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.balance }} 分</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="dialog-footer" slot="footer">
        <el-button @click="pointsDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserList,
  deleteUser,
  updateUserStatus,
  resetUserPassword,
} from '@/api/user'
import { getPointList } from '@/api/points'

export default {
  name: 'UserList',
  data() {
    return {
      searchForm: {
        username: '',
        phone: '',
        status: '',
      },
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 积分明细相关
      pointsDialogVisible: false,
      pointsLoading: false,
      currentUser: {},
      pointsRecords: [],
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.loading = true

      // 构建查询参数
      const params = {
        page: this.currentPage,
        limit: this.pageSize,
      }

      // 添加筛选条件
      if (this.searchForm.username) {
        params.username = this.searchForm.username
      }
      if (this.searchForm.phone) {
        params.phone = this.searchForm.phone
      }
      if (this.searchForm.status) {
        params.status = this.searchForm.status
      }

      // 调用API获取用户列表
      getUserList(params)
        .then(res => {
          if (res.code === 200) {
            this.tableData = res.data.list || []
            this.total = res.data.total || 0
          } else {
            this.$message.error(res.message || '获取用户列表失败')
          }
        })
        .catch(error => {
          console.error('获取用户列表出错', error)
          this.$message.error('获取用户列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchData()
    },
    resetSearch() {
      this.searchForm = {
        username: '',
        phone: '',
        status: '',
      }
      this.handleSearch()
    },
    handleEdit(row) {
      this.$router.push(`/user/add?id=${row.id}`)
    },
    handlePoints(row) {
      // 打开积分明细弹窗
      this.currentUser = { ...row }
      this.pointsDialogVisible = true
      this.fetchPointsRecords(row.id)
    },
    fetchPointsRecords(userId) {
      this.pointsLoading = true
      // 调用API获取积分记录
      getPointList({ userId, limit: 100 })
        .then(res => {
          if (res.code === 200) {
            this.pointsRecords = res.data.list || []
          } else {
            this.$message.error(res.message || '获取积分记录失败')
          }
        })
        .catch(error => {
          console.error('获取积分记录出错', error)
          this.$message.error('获取积分记录失败')
        })
        .finally(() => {
          this.pointsLoading = false
        })
    },
    handleDelete(row) {
      this.$confirm('确认删除该用户吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.loading = true
          deleteUser(row.id)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('删除成功')
                this.fetchData()
              } else {
                this.$message.error(res.message || '删除用户失败')
              }
            })
            .catch(error => {
              console.error('删除用户失败', error)
              this.$message.error('删除用户失败')
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {})
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    handleResetPassword(row) {
      this.$confirm('确认将该用户密码重置为123456吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.loading = true
          resetUserPassword(row.id)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('密码重置成功')
              } else {
                this.$message.error(res.message || '密码重置失败')
              }
            })
            .catch(error => {
              console.error('密码重置失败', error)
              this.$message.error('密码重置失败')
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {})
    },
  },
}
</script>

<style scoped>
.user-list-container {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 24px;
  background: #ffffff;
  border-radius: 8px;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0;
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section-card {
  background: #ffffff;
  padding: 24px;
  border-radius: 8px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
}

.delete-btn {
  color: #f53f3f;
}

.delete-btn:hover {
  color: #f76560;
}

/* 积分明细弹窗样式 */
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background-color: #f7f8fa;
  padding: 16px;
  border-radius: 4px;
}

.user-label {
  font-weight: 600;
  color: #606266;
  margin-right: 8px;
}

.user-value {
  color: #303133;
  margin-right: 24px;
}

.highlight {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.income {
  color: #67c23a;
  font-weight: bold;
}

.expense {
  color: #f56c6c;
  font-weight: bold;
}

/* 表格样式优化 */
.el-table th {
  background-color: #f7f7f7;
  color: #4d4d4d;
  font-weight: 600;
  height: 48px;
}

.el-table td {
  color: #666666;
  height: 56px;
}
</style> 